package com.tangkun.environment.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.RequestBody;
import com.tangkun.environment.R;
import com.tangkun.environment.adapter.ImageFileAdapter;
import com.tangkun.environment.entity.base.CommonReturn;
import com.tangkun.environment.entity.gongzuo.EnterpriseQueryReturn;
import com.tangkun.environment.entity.personcenter.UploadResourceReturn;
import com.tangkun.environment.network.MySubscribe;
import com.tangkun.environment.rx.RxActivityHelper;
import com.tangkun.environment.utils.JumpHelper;
import com.tangkun.environment.utils.LogUtils;
import com.tangkun.environment.utils.Utils;
import com.tangkun.environment.view.SquareGridView;

import org.simple.eventbus.EventBus;
import org.simple.eventbus.Subscriber;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import zxing.activity.MipcaCaptureActivity;

/**
 * 举报异常  创建异常
 */
public class JuBaoYiChangActivity extends BaseActivity {

    @BindView(R.id.back)
    ImageView back;
    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.next)
    TextView next;
    @BindView(R.id.squareGridView)
    SquareGridView squareGridView;
    @BindView(R.id.tv_jubaoyichang_name)
    AutoCompleteTextView tvJubaoyichangName;
    @BindView(R.id.et_jubaoyichang_neirong)
    EditText etJubaoyichangNeirong;
    @BindView(R.id.iv_jubaoyichang_erweima)
    ImageView ivJubaoyichangErweima;
    private Context mContext;

    /**
     * id 企业ID
     */
    private String id = "";
    /**
     * 名称ID
     */
    private String name = "";
    /**
     * 图片半路径地址，以逗号隔开
     */
    private String img = "";
    /**
     * 名称搜索列表数据源
     */
    private List<String> nameList = new ArrayList<String>();
    /**
     * 名称对应的id集合
     */
    private List<String> idList = new ArrayList<String>();
    /**
     * 名称搜索列表适配器
     */
    private ArrayAdapter<String> nameAdapter = null;
    /**
     * 图片列表适配器
     */
    private ImageFileAdapter adapter;

    // 最大图片上传张数
    private static final int IMAGE_NUM = 9;
    private static final int IMAGE_W = 400;
    private static final int IMAGE_H = 200;
    private static final int CAPTURE_IMAGE = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_yichang_add);
        mContext = this;
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);
        id = getIntent().getStringExtra("id");
        name = getIntent().getStringExtra("name");
        //名称
        if (!TextUtils.isEmpty(name)) {
            tvJubaoyichangName.setText(name);
        } else {
            tvJubaoyichangName.setText("");
        }
        if (!TextUtils.isEmpty(id)) {
            tvJubaoyichangName.setEnabled(false);
            ivJubaoyichangErweima.setEnabled(false);
        } else {
            tvJubaoyichangName.setEnabled(true);
            ivJubaoyichangErweima.setEnabled(true);
        }
        title.setText("举报异常");
        next.setText("确认");
        initView();
        initListener();
    }

    private void initView() {
        adapter = new ImageFileAdapter(this, R.layout.weibo_pic_list);
//        adapter.setCanDelete(true);
        adapter.setShowOriginal(false);//不显示原图
        adapter.getFileList();// initialize fileList
        Utils.setGridViewHeightBasedOnChildren(squareGridView, 3);
        // adapter.setShowOriginal(false);
        squareGridView.setAdapter(adapter);

        nameAdapter = new ArrayAdapter<String>(this,
                R.layout.item_dropdown_item, R.id.text1, nameList);
        tvJubaoyichangName.setAdapter(nameAdapter);
        tvJubaoyichangName.setThreshold(1);
    }

    private void initListener() {
        /**
         * 当输入关键字变化时，动态更新列表
         */
        tvJubaoyichangName.addTextChangedListener(new TextWatcher() {

            @Override
            public void afterTextChanged(Editable arg0) {

            }

            @Override
            public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {

            }

            @Override
            public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
                if (cs.length() <= 0) {
                    return;
                }
                enterpriseQuery();
            }
        });

        //点击事件
        tvJubaoyichangName.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
                //赋值ID
                id = idList.get(position);
            }
        });
    }

    /**
     * 搜索污染源
     */
    private void enterpriseQuery() {
        fromNetwork.enterpriseQuery(tvJubaoyichangName.getText().toString().trim())
                .compose(new RxActivityHelper<EnterpriseQueryReturn>().ioMain(JuBaoYiChangActivity.this, false))
                .subscribe(new MySubscribe<EnterpriseQueryReturn>(mContext, false) {
                    @Override
                    protected void success(EnterpriseQueryReturn resultBean) {
                        if (resultBean.data != null) {
                            nameList.clear();
                            idList.clear();
                            for (EnterpriseQueryReturn.DataBean bean : resultBean.data) {
                                if (!TextUtils.isEmpty(bean.ids)) {
                                    idList.add(bean.ids);
                                    if (!TextUtils.isEmpty(bean.name)) {
                                        nameList.add(bean.name);
                                    } else {
                                        nameList.add("");
                                    }
                                }
                            }
                            nameAdapter = new ArrayAdapter<String>(JuBaoYiChangActivity.this, R.layout.item_dropdown_item, R.id.text1, nameList);
                            tvJubaoyichangName.setAdapter(nameAdapter);
                            nameAdapter.notifyDataSetChanged();
                        }
                    }

                    @Override
                    protected void onMyError(String errorMessage) {
                        showToast(errorMessage);
                    }
                });
    }

    @OnClick({R.id.back, R.id.next, R.id.iv_jubaoyichang_erweima})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.back:
                Utils.hideSoftKeyboard(JuBaoYiChangActivity.this, back);
                JumpHelper.finish(mContext);
                break;
            case R.id.next://确认
                queding();
                break;
            case R.id.iv_jubaoyichang_erweima://二维码
                Intent intent = new Intent(JuBaoYiChangActivity.this, MipcaCaptureActivity.class);
                intent.putExtra("flag", 1);
                JumpHelper.jump(JuBaoYiChangActivity.this, intent, false);
                break;
        }
    }

    /**
     * 确定
     */
    private void queding() {
        if (TextUtils.isEmpty(id)) {
            showToast("请输入污染源名称");
            return;
        }
        if (TextUtils.isEmpty(etJubaoyichangNeirong.getText().toString().trim())) {
            showToast("请输入你想要举报的内容");
            return;
        }
        if (adapter.getFileList() != null && adapter.getFileList().size() > 0) {//有图片调用上传图片接口，图片全部上传完成后调用创建咨询接口
            for (File file : adapter.getFileList()) {
                sendPhotoToServer(file.getPath());
            }
        } else {//没有图片直接调用创建咨询接口
            reportSave();
        }
    }

    /**
     * 创建异常举报
     */
    private void reportSave() {
        if (TextUtils.isEmpty(id)) {
            showToast("");
            return;
        }
        Map<String, String> map = new HashMap<>();
        map.put("id", id);//污染源对应ID
        map.put("content", etJubaoyichangNeirong.getText().toString().trim());
        map.put("reportimgs", img);//上传图片半路径，以逗号隔开
        fromNetwork.reportSave(map)
                .compose(new RxActivityHelper<CommonReturn>().ioMain(JuBaoYiChangActivity.this, true))
                .subscribe(new MySubscribe<CommonReturn>(mContext, true) {
                    @Override
                    protected void success(CommonReturn resultBean) {
                        //tangkun 发出通知 刷新异常举报列表
                        EventBus.getDefault().post(true, "YiChangShuJuTiJaoActivity.refresh");
                        showToast("举报成功");
                        Utils.hideSoftKeyboard(JuBaoYiChangActivity.this, back);
                        JumpHelper.finish(mContext);
                    }

                    @Override
                    protected void onMyError(String errorMessage) {
                        showToast(errorMessage);
                    }
                });
    }


    /**
     * 上传图片到服务器
     *
     * @param filePath 本地图片路径
     */
    private synchronized void sendPhotoToServer(String filePath) {
        String[] filePathArray = filePath.split("/");
        //文件名
        String fileName = filePathArray[filePathArray.length - 1];
        fileName = fileName + ".png";//加上.png后缀名
        LogUtils.e("文件名称：" + fileName);
        //生成文件
        File file = new File(filePath);
        //组装partMap对象
        Map<String, RequestBody> partMap = new HashMap<>();
        RequestBody fileBody = RequestBody.create(MediaType.parse("image/*"), file);//文件
//        partMap.put("file", fileBody);//文件名
        partMap.put("file\"; filename=\"" + fileName + "", fileBody);//文件名
//        RequestBody dirBody = RequestBody.create(MediaType.parse("text/plain"), "user/header");//dir参数值
//        RequestBody fileNameBody = RequestBody.create(MediaType.parse("text/plain"), fileName);//文件名参数值
//        partMap.put("dir", dirBody);//dir参数
//        partMap.put("fileName", fileNameBody);//dir参数
        fromNetwork.uploadImageReport(partMap).compose(new RxActivityHelper<UploadResourceReturn>().ioMain(JuBaoYiChangActivity.this, true))
                .subscribe(new MySubscribe<UploadResourceReturn>(mContext, true) {
                    @Override
                    protected void success(UploadResourceReturn uploadResourceReturn) {
                        if (uploadResourceReturn.data != null) {
                            if (uploadResourceReturn.data.size() > 0) {
                                //文件上传成功，返回的图片半路径，拼接成图片集合
                                if (TextUtils.isEmpty(img)) {
                                    img = uploadResourceReturn.data.get(0).url;
                                } else {
                                    img = img + "," + uploadResourceReturn.data.get(0).url;
                                }
                                //图片全部上传完成，调用创建咨询接口
                                if (img.split(",").length == adapter.getFileList().size()) {
                                    reportSave();
                                }
                            }
                        }
                    }

                    @Override
                    protected void onMyError(String errorMessage) {
                        showToast(errorMessage);
                    }
                });
    }

    @SuppressWarnings("unchecked")
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        // 刷新来自相册列表选中的图片列表
        if (requestCode == ImageFileAdapter.REQUEST_CODE_CAPTURE_IMAGE && resultCode == CaptureImageActivity.CAPTURE) {
            List<File> list = (List<File>) data.getSerializableExtra("fileList");
            if (list != null) {
                adapter.getFileList().addAll(list);
                adapter.notifyDataSetChanged();
                Utils.setGridViewHeightBasedOnChildren(squareGridView, 3);
            }
        }

        // 刷新有过删除后的图片列表
        if (requestCode == ImageFileAdapter.REQUEST_CODE_CAPTURE_IMAGE && resultCode == DeleteImageActivity.RESULT_CODE_DELETE_CHANGED) {
            List<File> fileList = new ArrayList<File>();
            fileList = (List<File>) data.getSerializableExtra("fileList");
            if (fileList != null) {
                adapter.setFileList(fileList);
            }
            Utils.setGridViewHeightBasedOnChildren(squareGridView, 3);
            adapter.notifyDataSetChanged();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    //通过扫码获取到企业ID和名称
    @Subscriber(tag = "JuBaoYiChangActivity.refreshIdAndName")
    private void refreshIdAndName(Intent intent) {
        name = intent.getStringExtra("name");
        id = intent.getStringExtra("id");
        if (!TextUtils.isEmpty(name)) {
            tvJubaoyichangName.setText(name);
        } else {
            tvJubaoyichangName.setText("");
        }
    }

}
